package com.spark.laboratory.utils;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Date;


public class TESTOKHttp {
 
	 /**
     * 调用对方接口方法
      * @param path 对方或第三方提供的路径
      */
    public static void interfaceUtil(String path) {
        String str = "";

        try {
            URL url = new URL(path);
            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            PrintWriter out = null;
            
            /**设置URLConnection的参数和普通的请求属性****start***/
           
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");

            /**设置URLConnection的参数和普通的请求属性****end***/

            conn.setDoOutput(true);
            conn.setDoInput(true);
            
            conn.setRequestMethod("GET");//GET和POST必须全大写

            conn.connect(); 

            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            while ((str = br.readLine()) != null) {
            	str = new String(str.getBytes(),"UTF-8");//解决中文乱码问题
                System.out.println(new Date() + "-----" +  str);
            }
            //关闭流
            is.close();
            //断开连接，最好写上，disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
            //固定多线程的话，如果不disconnect，链接会增多，直到收发不出信息。写上disconnect后正常一些。
            conn.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    
    public static void main(String[] args) throws IOException, JSONException {


//        CloseableHttpClient httpclient = HttpClients.createDefault();
//        HttpGet httpGet = new HttpGet("http://www.ilab-x.com/project/log/upload?xjwt=" + data);
//        CloseableHttpResponse response = httpclient.execute(httpGet);
//
//        String respCtn = EntityUtils.toString(response.getEntity());
//
//        System.out.println(respCtn);

//        System.out.println(userCheck("18779919269", "lxz20009290."));

//        interface_2("mj_2586688");

    }

    public static JSONObject userCheck(String username, String password) {
        String nonce = JWTUtils.getRandomString();
        String cnonce = JWTUtils.getRandomString();

        String sha256 = Sha256.getSHA256(nonce + Sha256.getSHA256(password).toUpperCase() + cnonce).toUpperCase();

        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            String respCtn = "";
            HttpResponse response = null;
            HttpGet httpGet = new HttpGet("http://www.ilab-x.com/sys/api/user/validate?nonce="
                    + nonce + "&cnonce=" + cnonce + "&username=" + username + "&password=" + sha256);
            response = httpclient.execute(httpGet);
            respCtn = EntityUtils.toString(response.getEntity());

            return new JSONObject(respCtn);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    public static void interface_2(String username) throws JSONException {
        JSONObject param = new JSONObject();
        param.put("username", username);
        param.put("issuerId",KEY.issueId);

        String json = param.toString();

        String data = null;
        try {
            data = encrtya(json);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println(new Date() + "-----" + data);
        //        System.out.println(s);

        interfaceUtil("http://www.ilab-x.com/third/api/test/result/upload?xjwt=" + data);
    }

    @Test
    public void test11() throws JSONException {
        interface_1(
                "李熙政",
                100,
                1596211200000L,
                1596211800000L,
                10);
    }

    public static void interface_1(String username,
                                   Integer score,
                                   Long startDate,
                                   Long endDate,
                                   Integer timeUsed
                                   ) throws JSONException {
        JSONObject param=new JSONObject();
        param.put("username",username);
        param.put("projectTitle","特种铸造虚拟仿真实验");
        param.put("status","1");
        param.put("score",score);
        param.put("startDate",startDate);
        param.put("endDate",endDate);
        param.put("timeUsed",timeUsed);
        param.put("issuerId","102851");
        String json = param.toString();

        String data = null;
        try {
            data = encrtya(json);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println(new Date() + "-----" + data);
        //        System.out.println(s);

        interfaceUtil("http://www.ilab-x.com/project/log/upload?xjwt=" + data);
    }


    public static String encrtya(String json) throws Exception {
        //获取当前时间
        long now=System.currentTimeMillis();
        //创建JWT实例
        JWT jwt=new JWT(KEY.secret,KEY.aeskey,now,KEY.issueId);
        //创建payload
        ByteBuffer payload = ByteBuffer.allocate(1024).order(ByteOrder.BIG_ENDIAN);
        payload.put(json.getBytes("UTF-8")).flip();
        //创建out
        ByteBuffer out = ByteBuffer.allocate(1024);
        //加密数据
        jwt.encryptAndSign(JWT.Type.SYS,payload,out,now+10*60*1000); //设置过期时间，例:10分钟
        String xjwt = new String(out.array(),out.arrayOffset(),out.remaining());
        //对数据进行url 编码
        return URLEncoder.encode(xjwt,"UTF-8");
    }

}